package com.easyj.admin.sys.serviceimpl;

import java.util.List;
import java.util.Set;
import java.util.Date;
import java.util.HashMap;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.easyj.admin.sys.service.PositionService;
import com.easyj.admin.db.mapper.PositionMapper;
import com.easyj.admin.db.mapper.UserPositionMapper;
import com.easyj.base.common.imp.ImpExcutor;
import com.easyj.base.common.imp.ImpUtils;
import com.easyj.base.exception.*;
import com.easyj.base.security.service.SecurityUtil;
import com.easyj.admin.db.model.ImpResult;
import com.easyj.admin.db.model.Position;
import com.easyj.admin.db.model.User;


@Service
public class PositionServiceImpl implements PositionService{
    private final String CahceName="bean_cache_Position";
	
	@Autowired
	private  PositionMapper positionMapper;
	
	@Autowired
	private  UserPositionMapper userPositionMapper;
	

   	public List<Position> findList(Position filter){
        return positionMapper.selectByExample(filter);
    }
	public long count(Position filter){
	     return positionMapper.countByExample(filter);
	}	

	@Cacheable(value=CahceName,key="#id")
	public Position findById(Long id){
		Position entity= positionMapper.selectByPrimaryKey(id);
		return entity;
	}
	

	@Transactional
	public int  insertEntity(Position entity) throws EasyjException{
		//唯一....
		if(selectUniqueByUqCode(entity.getCode())!=null) {
			throw new ValidateException(EasyjException.SameCode,"代码："+entity.getCode()+"已存在");
		}
		//唯一....
		if(selectUniqueByUqName(entity.getName())!=null) {
			throw new ValidateException(EasyjException.SameCode,"名称："+entity.getCode()+"已存在");
		}
		entity.setIsSystem(false);
	    entity.setCreateTime(new Date());
		entity.setOperatorId(SecurityUtil.getOperatorId());	
		int rtn= positionMapper.insert(entity);
		return rtn;
	}
	
	@CacheEvict(value=CahceName, key="#entity.id")
	@Transactional
	public int  updateEntity(Position entity) throws EasyjException{
		Position old= positionMapper.selectByPrimaryKey(entity.getId());
	    if(old.getIsSystem()) {
	    	throw new UpdateSystemObjectException();
	    }
		//唯一.....不可修改
		//Position f0=selectUniqueByUqCode(entity.getCode());
  		//if(f0!=null && f0.getId().longValue()!=entity.getId().longValue()) {
  		//	throw new ValidateException(EasyjException.SameCode,"代码："+entity.getCode()+"已存在");
  		//}
		//唯一.....
		Position f=selectUniqueByUqName(entity.getName());
  		if(f!=null && f.getId().longValue()!=entity.getId().longValue()) {
  			throw new ValidateException(EasyjException.SameCode,"名称："+entity.getCode()+"已存在");
  		}
	    entity.setModifyTime(new Date()); 
		entity.setOperatorId(SecurityUtil.getOperatorId());	
		int rtn= positionMapper.updateByPrimaryKey(entity);
		return rtn;
	}
    /**
     * 数据表建立外键约束，限定删除
     */
    @CacheEvict(value=CahceName, key="#id")
	@Transactional
	public int  deleteById(Long id) throws EasyjException{
    	Position old= positionMapper.selectByPrimaryKey(id);
	    if(old.getIsSystem()) {
	    	throw new UpdateSystemObjectException();
	    }

	    if( userPositionMapper.countByPositionId(id)>0l) {
			throw new ValidateException("岗位在使用，不能删除！");
		}
		int rtn= positionMapper.deleteByPrimaryKey(id);
		return rtn;
	}


	public Position  selectUniqueByUqCode(String code){
	   Position entity= positionMapper.selectUniqueByUqCode(code);
	   return entity;
	}
	
	public Position  selectUniqueByUqName(String name){
	   Position entity= positionMapper.selectUniqueByUqName(name);
	   return entity;
	}
	
    public List<User> findUsersByPositionId(Long positionId){
    	return  userPositionMapper.selectUsersByPositionId(positionId);
    }
    
    public List<User> findUsersByPositionCode(String positionCode){
    	return userPositionMapper.selectUsersByPositionCode(positionCode);
    }
    
    /**
     * //导入数量一般较少，同步执行导入
	 * import from excel
	 * @param excelfile
	 * @param operatorId
	 * @return
	 * @throws Exception
	 */
	public ImpResult importExcel(MultipartFile excelfile,Long operatorId) throws Exception{
		ValidatorFactory factory=Validation.buildDefaultValidatorFactory();
		final Validator validator =factory.getValidator(); 
		ImpExcutor<Position> impExcutor=new ImpExcutor<Position>("岗位",operatorId,false){//不保存导出结果

				@Override
				protected Position getAndValidateBean(Row row) throws ImpValidException {
					HashMap<String,String> errmap=new HashMap<String,String>();
					//set bean value
					Position bean=new Position();
					
					//直接设值
					ImpUtils.setObjectValueByRow(row, fields, bean);
					
					//valid
					Set<ConstraintViolation<Position>> constraintViolations = validator.validate(bean);
					if(CollectionUtils.isNotEmpty(constraintViolations)){
						for(ConstraintViolation<Position> e:constraintViolations){
							if(e.getPropertyPath()!=null){
								errmap.put(e.getPropertyPath().toString(), e.getMessage());
							}
						}
						
					}
					//has error then throw excepton
	                if(errmap.size()>0) {
	                	throw new ImpValidException("数据不符合规范",errmap);
	                }
					
					return bean;
				}
	
				@Override
				protected int save(Position bean) throws Exception{
					try {
					  bean.setOperatorId(operatorId);	
					  return insertEntity(bean);	
					}catch(ValidateException e ) {
						HashMap<String,String> errmap=new HashMap<String,String>();
						errmap.put("code", e.getMessage());
						throw new ImpValidException("",errmap);
					}
				}
		};
	
         ImpResult rtn=impExcutor.initImport(excelfile, "position.xml");
		
		//同步执行导入
         impExcutor.execImport();
		
		 return rtn;
	}
	
	
}
